<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDepartmentsByKeyWord">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-perm="'department:save'" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 默认name="file" -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/department/importExcel"
                     list-type="text">
            <el-button type="warning">点击导入</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="depts" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="name" label="部门名">
      </el-table-column>
      <el-table-column prop="sn" label="编号">
      </el-table-column>
      <el-table-column label="状态" >
        <template scope="scope">
          <span v-if="scope.row.state" style="color: green">正常</span>
          <span v-if="!scope.row.state" style="color: red">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" >
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" v-perm="'department:save'" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" v-perm="'department:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增界面-->
    <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门经理" >
            <el-select v-model="addForm.managerId" @change="$forceUpdate()" placeholder="请选择">
              <el-option
                  v-for="item in managers"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
            <el-cascader
                clearable
                v-model="addForm.parentId"
                :options="options"
                :props="{'value':'id','label':'name', checkStrictly: true}"
               ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      //部门分页列表
      depts: [],
      total: 0,
      currentPage: 1,
      pageSize:10,
      listLoading: false,
      sels: [],//列表选中列
      managers:[],//部门经理列表
      title:"",//弹出框标题
      options: [],//部门列表（无限级树）
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        name: '',
        sn: '',
        managerId: '',
        parentId:''
      }

    }
  },
  methods: {
    getDepartmentsByKeyWord(){
      this.currentPage = 1;
      this.getDepartments();
    },

    //当页码发生改变的时候，触发事件
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取用户列表
    getDepartments() {
      //开启加载框
      this.listLoading = true;
      var param = {
        "currentPage":this.currentPage,
        "pageSize":this.pageSize,
        "keyword":this.filters.keyword
      }
      this.$http.patch("/department",param).then(res=>{
        var {success,resultObj} = res.data;
        if(success){
          this.depts = resultObj.results;
          this.total = resultObj.total;
        }
        //关闭加载框
        this.listLoading = false;
      })
    },
    //显示所有的部门经理
    getEmployees(){
        this.$http.patch("/employee/queryAllEmployee").then(res=>{
          var {success,resultObj} = res.data;
          if(success){
              this.managers = resultObj;
          }
        })
    },
    //显示部门的无限极树
    getTree(){
      this.$http.patch("/department/queryTree").then(res=>{
        var {success,resultObj} = res.data;
        if(success){
          this.options = resultObj;
        }
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/"+row.id).then(res=>{
          var {success,resultObj} = res.data;
          //如果成功
          if(success){
            //刷新界面
            this.getDepartments();
          }else{
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          }
          this.listLoading = false;
        })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // //设置标题
      this.title = "修改";

      //回显数据
      this.addForm = Object.assign({}, row);

      //如果manager有值，就回显部门经理
      if(this.addForm.manager){
          this.addForm.managerId = this.addForm.manager.id;
      }
      if(this.addForm.parent){
        //获取层级路径
        var dirPath = this.addForm.dirPath;
        //以/进行切割
        var dirPaths = dirPath.split("/");

        //上级层次用一个数组来装
        var parentIds = [];
        for(var i=0;i<dirPaths.length-1;i++){
          if(dirPaths[i]){
            parentIds.push(parseInt(dirPaths[i]));
          }
        }
        //给上级部门赋值
        this.addForm.parentId = parentIds;

      }
      if(this.$refs["addForm"]){
        // //清空校验
        this.$refs["addForm"].clearValidate();
      }
      //显示模态框
      this.addFormVisible = true;

    },
    //显示新增界面
    handleAdd: function () {
      //设置标题
      this.title = "新增";
      //显示模态框
      this.addFormVisible = true;
      //循环addForm对象，对内部的属性值，进行清空
      for(let key in this.addForm){
        this.addForm[key] = "";
      }
      //清空校验
      this.$refs["addForm"].clearValidate();

    },
    //新增
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
            let para = Object.assign({}, this.addForm);
            //如果没有选中父级，那就不提交该属性
            if(!para.parentId){
                delete para["parentId"];
            }
            this.$http.put("/department/save",para).then(res=>{
              var {success,resultObj} = res.data;
              if(success){
                  //关闭窗口
                  this.addFormVisible = false;
                  //刷新界面
                  this.getDepartments();
                  //刷新部门树
                  this.getTree();
              }else{
                this.$message({
                  message: '提交失败',
                  type: 'error'
                });
              }
            })
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/department/batchDelete",this.sels).then(res=>{
            var {success,resultObj} = res.data;
            //如果成功
            if(success){
              //刷新界面
              this.getDepartments();
            }else{
              this.$message({
                message: '删除失败',
                type: 'error'
              });
            }
            this.listLoading = false;
        })

      }).catch(() => {

      });
    }
  },
  mounted() {
    //部门列表分页查询
    this.getDepartments();
    //显示所有的部门经理
    this.getEmployees();
    //显示部门列表的无限极树
    this.getTree();
  }
}

</script>

<style scoped>

</style>